package com.zx.model.log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.zx.util.Assert;

/**
 * @Project: ngnix_analyze
 * @Title: LogPv
 * @Description: 日志分析--
 * 			pv（一天内网站被访问的次数）
 * 			uv（一天内网站被访问的次数,进行IP去重）
 * @author: zhangxue
 * @date: 2018年8月2日下午10:29:57
 * @company: alibaba
 * @Copyright: Copyright (c) 2015
 * @version v1.0
 */
public class LogPvAndUv implements java.lang.Comparable<LogPvAndUv>{
	/** 时间，yyyy-MM-dd */
	private Date date;

	/** 时间，yyyy-MM-dd */
	private String dateStr;

	/** 某一天的点击量 */
	private Integer pv;
	
	/** 某一天的点击量（一个用户记录一次） */
	private Integer uv;

	private final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");
	
	/**
	 * 获得日志中对IP的分析
	 * @param list
	 * @return key=ip, value=次数
	 * @date: 2018年8月1日下午11:55:16
	 */
	public static List<LogPvAndUv> stat(List<LogMode> list){
		List<LogPvAndUv> result = new ArrayList<>();
		if(Assert.isEmpty(list)) {
			return result;
		}
		// 分类统计
		Map<String, Integer> pvMap = new HashMap<>();//key=yyyy-MM-dd, value=日志的数量
		Map<String, Set<String>> uvMap = new HashMap<>();//key=yyyy-MM-dd, value=ip的数量
		
		for (LogMode logMode : list) {
			String userIp = logMode.getRemoteAddr();
			String dateStr = SDF.format(logMode.getTimeLocalDate());
			
			Integer pv = pvMap.get(dateStr);
			if(pv == null) {
				pvMap.put(dateStr, 1);
			} else {
				pvMap.replace(dateStr, pv + 1);
			}
			Set<String> uv = uvMap.get(dateStr);
			if(uv == null) {
				uv = new HashSet<>();
				uv.add(userIp);
				uvMap.put(dateStr, uv);
			} else {
				uv.add(userIp);
			}
		}
		
		// 转为list
		for (String key :pvMap.keySet()) {
			try {
				Integer pv = pvMap.get(key);
				Integer uv = uvMap.get(key).size();
				String dateStr = key;
				Date date = SDF.parse(dateStr);
				result.add(new LogPvAndUv(date, dateStr, pv, uv));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		// 排序，默认降序排序
		Collections.sort(result);
		return result;
	}
	
	public LogPvAndUv(Date date, String dateStr, Integer pv, Integer uv) {
		this.date = date;
		this.dateStr = dateStr;
		this.pv = pv;
		this.uv = uv;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public String getDateStr() {
		return dateStr;
	}

	public void setDateStr(String dateStr) {
		this.dateStr = dateStr;
	}

	public Integer getPv() {
		return pv;
	}

	public void setPv(Integer pv) {
		this.pv = pv;
	}

	public Integer getUv() {
		return uv;
	}

	public void setUv(Integer uv) {
		this.uv = uv;
	}

	@Override
	public String toString() {
		return "{'date':'" + dateStr + "', 'pv':" + pv + ", 'uv':" + uv + "}";
	}

	@Override
	public int compareTo(LogPvAndUv o) {
		return ~((Long) this.getDate().getTime())
				.compareTo(o.getDate().getTime());
	}
	
}
